<script lang="ts" setup>
import { useGlobalDialog } from '@/hooks'
import { initPageDTO, initPageVO, type PageDTO, type PageVO, type ResultType } from '@/type/type'
import {
  addLabelApi,
  delLabelApi,
  getLabelAdminPageApi,
  initLabelDTO,
  type LabelDTO,
  type LabelVO,
  labelVO2DTO,
  updateLabelApi
} from '@/request/api/label'
import { ClassifyEnum, DialogEnum } from '@/enum'
import { useSystemStore } from '@/stores/system'
import { useTemporaryStore } from '@/stores/temporary'

const { globalDialog } = useGlobalDialog()
const systemStore = useSystemStore()
const temporaryStore = useTemporaryStore()
// 表单
const form = ref<LabelDTO>(initLabelDTO())
const formRef = ref<any>()
// 多选框 id
const ids = ref<number[]>([])
const isAdd = ref<boolean>(false)
/** 查询列表 */
const pageVO = ref<PageVO<LabelVO>>(initPageVO())

const page = ref<PageDTO>(initPageDTO())

const rules = {
  name: [{ required: true, message: '名字不能为空', trigger: 'blur' }],
  classifyId: [{ required: true, message: '类别不能为空', trigger: 'blur' }],
  introduction: [{ required: true, message: '简介不能为空', trigger: 'blur' }]
}

const getList = () => {
  getLabelAdminPageApi(page.value).then((res: ResultType<PageVO<LabelVO>>) => {
    pageVO.value = res.data
  })
}
// 多选框选中数据
const handleSelectionChange = (selection: LabelVO[]) => {
  ids.value = selection.map((item) => item.id)
}

/** 新增、修改按钮操作 */
const handle = (add: boolean, row?: LabelVO) => {
  form.value = initLabelDTO()
  systemStore.dialog.label = true
  isAdd.value = add
  if (!add && row) {
    form.value = labelVO2DTO(row)
    temporaryStore.form.classifyId = form.value.classifyId || -1
  }
}

/** 提交按钮 */
function submitForm() {
  form.value.classifyId = temporaryStore.form.classifyId
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.id != undefined) {
        await globalDialog('确定修改 ID 为"' + form.value.id + '"的标签?').then((res: boolean) => {
          if (res) {
            updateLabelApi(form.value).then(() => {
              systemStore.dialog.label = false
              getList()
            })
          }
        })
      } else {
        await addLabelApi(form.value).then(() => {
          systemStore.dialog.label = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
const handleDelete = async (idArr: Array<number>) => {
  await globalDialog('确定删除 ID 为"' + idArr + '"的标签?').then((res: boolean) => {
    if (res) {
      delLabelApi(idArr).then((res: ResultType<boolean>) => {
        if (res.data) {
          getList()
        }
      })
    }
  })
}

/** 启用停用按钮操作 */
const handleChangeStatus = async (id: number, status: boolean) => {
  const dto: LabelDTO = initLabelDTO()
  dto.id = id
  dto.status = status
  const title = status ? '启用' : '停用'
  await globalDialog('确定' + title + ' ID 为"' + id + '"的标签?').then((res: boolean) => {
    if (res) {
      updateLabelApi(dto).then((res: ResultType<boolean>) => {
        if (res.data) {
          getList()
        }
      })
    }
  })
}

onMounted(() => {
  getList()
})
</script>

<template>
  <el-container class="pt-5 gap-3" direction="vertical">
    <el-container class="pb-2 px-5" direction="vertical">
      <QueryForm
        :search="getList"
        :type="ClassifyEnum.NULL"
        @update="
          (args: Record<string, any>) => {
            page.param = args
          }
        "
      />
      <el-container class="gap-3">
        <el-button class="!px-2 !m-0" plain type="primary" @click="handle(true)">
          <SvgIcon message="新增" name="add" />
        </el-button>
        <el-button
          :disabled="ids.length === 0"
          class="!px-2 !m-0"
          plain
          type="danger"
          @click="handleDelete(ids)"
        >
          <SvgIcon message="删除" name="delete" />
        </el-button>
      </el-container>
    </el-container>

    <el-table :data="pageVO.list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="35" />
      <el-table-column label="标签名" prop="name" width="240" />
      <el-table-column label="类别名" prop="classifyName" width="120" />
      <el-table-column label="简介" prop="introduction" />
      <el-table-column label="状态" prop="status" width="70">
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'success' : 'danger'">
            {{ scope.row.status ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="110">
        <template #default="scope">
          <el-button class="!p-2 !m-1" type="primary" @click="handle(false, scope.row)">
            <SvgIcon name="edit" />
          </el-button>
          <el-button
            v-if="!scope.row.status"
            class="!p-2 !m-1"
            type="success"
            @click="handleChangeStatus(scope.row.id, true)"
          >
            <SvgIcon name="refresh" />
          </el-button>
          <el-button
            v-else
            class="!p-2 !m-1"
            type="danger"
            @click="handleChangeStatus(scope.row.id, false)"
          >
            <SvgIcon name="error" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <PageBox
      :total="pageVO.total"
      @update="
        (args: PageDTO) => {
          page = args
          getList()
        }
      "
    />
    <!-- 添加或修改对话框 -->
    <DialogTemplate :attribute="DialogEnum.LABEL" :title="isAdd ? '新增标签' : '修改标签'">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item label="标签名" prop="name">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item>
        <ClassifyLabelForm :show-label="false" :type="ClassifyEnum.NULL" />
        <el-form-item label="简介" prop="introduction">
          <el-input
            v-model="form.introduction"
            :rows="10"
            maxlength="200"
            placeholder="请输入"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <el-container class="justify-between">
        <el-button type="info" @click="systemStore.dialog.label = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </el-container>
    </DialogTemplate>
  </el-container>
</template>
